import { updateCommentUsingPost } from '@/services/backend/commentController';
import { ProColumns, ProFormInstance, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Modal } from 'antd';
import React, { useRef } from 'react';

interface Props {
  oldData?: API.Comment;
  modalVisible: boolean;
  columns: ProColumns<API.Comment>[];
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.CommentUpdateRequest) => {
  const hide = message.loading('正在更新');
  try {
    await updateCommentUsingPost({
      ...fields,
    });
    hide();
    message.success('更新成功');
    return true;
  } catch (error: any) {
    hide();
    message.error(`更新失败${error.message}`);
    return false;
  }
};

const UpdateModal: React.FC<Props> = (props) => {
  const { modalVisible, columns, onSubmit, onCancel, oldData } = props;

  const formRef = useRef<ProFormInstance>();

  return (
    <Modal
      title={'更新'}
      open={modalVisible}
      destroyOnClose
      footer={null}
      onCancel={onCancel}
      width={800}
    >
      <ProTable
        type={'form'}
        formRef={formRef}
        columns={columns}
        form={{ initialValues: oldData }}
        onSubmit={async (value) => {
          const success = await handleUpdate({
            ...value,
            id: oldData?.id,
          });
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};
export default UpdateModal;
